package com.huiquan.management.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.foundation.constant.RoleID;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.constant.BaseContants;
import com.huiquan.management.dao.UserAbilityDao;
import com.huiquan.management.domain.UserAbility;
import com.huiquan.onlineTime.service.OnlineTimeRecordService;

@Service
public class UserAbilityService extends BaseService {

	@Autowired
	private UserAbilityDao userAbilityDao;

	public UserAbility getAbilityByUserId(Long userId, Integer roleId) {

		UserAbility ability = userAbilityDao.retrieveObjectByUserIdAndRuleId(userId, roleId);

		return ability;
	}

	public void initByUserIdAndRoleId(Long userId, Integer roleId) {

		UserAbility ability = getAbilityByUserId(userId, roleId);

		// 不需要有能力记录的权限
		List<Integer> noAbilityRoleIdList = new ArrayList<>();
		noAbilityRoleIdList.add(RoleID.NONE.getId());
		noAbilityRoleIdList.add(RoleID.ADMIN.getId());

		// 直接通过测试的权限
		List<Integer> passTestList = new ArrayList<>();
		passTestList.add(RoleID.OUTSOURCE_XBS_IMAGEOLOGY_CHECK.getId());
		passTestList.add(RoleID.OUTSOURCE_QA.getId());

		if (ability == null && !noAbilityRoleIdList.contains(roleId)) {
			int examPass = BaseContants.FLAG_NO;
			if (passTestList.contains(roleId)) {
				examPass = BaseContants.FLAG_YES;
			}
			userAbilityDao.initByUserIdAndRoleId(userId, roleId, examPass);
		}
	}

	public ModelAndView incapable(HttpServletResponse resp, HttpServletRequest req) throws Exception {

		req.getRequestDispatcher("/WEB-INF/vm/incapable.html").forward(req, resp);

		return null;
	}

	public void pass(User user) {

		// 修改是否通过测验字段
		userAbilityDao.updatePassFlagByUidAndRole(BaseContants.FLAG_YES, user.getUserId(), user.getRole());

		// 维护在线时间记录中该用户的是否计时状态
		OnlineTimeRecordService.putIncapableFlag(user, false);

	}

}
